<template>
  <div>
    <el-table :data="tableData" :tooltip-effect="tooltipEffect" style="width: 100%"
      @selection-change="handleSelectionChange" @select="pinSelect" ref="multipleTable" border
      @header-dragend="headerDragend">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column v-for="(column, index) in columns" :key="index" :prop="column.prop" :label="column.label"
        :width="column.width" :show-overflow-tooltip="column.showTooltip"></el-table-column>
      <slot />
    </el-table>
  </div>
</template>

<script>
export default {
  name: 'CustomElementTable',
  props: {
    tableData: {
      type: Array,
      required: true
    },
    columns: {
      type: Array,
      required: true
    },
    tooltipEffect: {
      type: String,
      default: 'dark'
    }
  },
  data() {
    return {
      origin: -1,
      pin: false,
      multipleSelection: []
    }
  },
  methods: {
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;

    },
    pinSelect(item, index) {
      const data = this.$refs.multipleTable.tableData;
      const origin = this.origin;
      const endIdx = index.index;
      if (this.pin && item.includes(data[origin])) {
        const sum = Math.abs(origin - endIdx) + 1;
        const min = Math.min(origin, endIdx);
        let i = 0;
        while (i < sum) {
          const index = min + i;
          this.$refs.multipleTable.toggleRowSelection(data[index], true);
          i++;
        }
      } else {
        this.origin = index.index;
      }
    },
    headerDragend(newWidth, oldWidth, column, event) {
      // 饿了么UI中提供的有对应参数，主要用到的是newWidth和column.property
      console.log(newWidth, oldWidth, column, event);

      // 根据column中的信息就可以知道用户拖动的是哪一列，从而将新的列宽度替换原来的列宽度
      let newTableHeader = this.columns.map((item, index) => {
        if (item.label == column.property) {
          item.width = newWidth;
        }
        return item;
      });

      // 最后存一份到本地，当刷新的时候，就用本地的这个记录了用户拖动宽度的表头数组数据
      sessionStorage.setItem("tableHeader", JSON.stringify(newTableHeader));
    },
  },
  mounted() {
    window.addEventListener('keydown', code => {
      if (code.keyCode === 16 && code.shiftKey) {
        this.pin = true;
      }
    });
    window.addEventListener('keyup', code => {
      if (code.keyCode === 16) {
        this.pin = false;
      }
    });
  },
  created() {
    this.tableData.forEach((item, index) => {
      item.index = index;
    })
  }
}
</script>

<style scoped></style>
